<?php 
class setting_models_option extends CI_Model{
	public function __construct(){
		$this->load->database();
	}
	public function listOption($search){
		$this->db->select('*')->
					from('options')->
					where('parent',0)->
					order_by('name', "desc");
		if(!empty($search)){
			$this->db->like('name', $search);
			$this->db->or_like('value', $search);
		}
		$get= $this->db->get();
		$array=array();
		foreach ($get->result() as $row){
			$array[]=$row;
			$this->db->select('*')->
						from('options')->
						where('parent',$row->id_type)->
						order_by('name', "desc");
			$getChild= $this->db->get();			
			if($getChild->num_rows()){
				
				foreach ($getChild->result() as $rowChild){
					$rowChild->name='└─ '.$rowChild->name;
					$array[]=$rowChild;
				}
			}
		}
		return $array;
	}
	public function listOptionParent(){
		$this->db->select('*')->
					from('options')->
					where('parent' , 0)->
					order_by('name', "desc");
		$get = $this->db->get();
		return $get->result();
	}
	
	public function get_options($id_options_category){

		$this->db->select('option')->
					from('category')->
					where('id',$id_options_category);
		$get= $this->db->get();
		$row=$get->result();
		if(empty($row)) return false;
		$id_options=$row[0]->option;

		if(!$id_options) return false;
		
		$this->db->select('*')->
					from('options')->
					where_in('id_type',explode(',',$id_options));
		$get= $this->db->get();
		
		$order =array_flip(explode(',',$id_options));
		
		foreach ($get->result() as $row)
			$order[$row->id_type]= $row;
		
		return $order;
	}
	public function get_Filters($id_options_category){
		if(!is_numeric($id_options_category)) return false;
		$this->db->select('*')->
					from('category')->
					where('id',$id_options_category)->
					order_by('name', "desc");
		$get= $this->db->get();
		$row=$get->result();
		$id_options=$row[0]->option;

		if(!$id_options) return false;
		
		 $sql="
				SELECT  *  
				FROM `options` 
				WHERE `id_type` IN ($id_options) and 
						id_type not in (
								SELECT  distinct parent  
								FROM `options` 
								WHERE `id_type` IN ($id_options)
					)";
		$query = $this->db->query($sql);
		$order =array_flip(explode(',',$id_options));
		
		foreach ($query->result() as $row)
			$order[$row->id_type]= $row;
		foreach ($order as $id=>$testObject)
			if(!is_object($testObject)) unset($order[$id]);
			
		return $order;
		
	}
	public function add_options($data){
		$this->db->insert('options', $data);
		return $this->db->insert_id();
	}
	public function update_options($data){
		if(isset($data['id'])){
			$this->db->where('id_type', $data['id']);
			unset($data['id']);
			$this->db->update('options', $data);
			return $this;
		}
	
	}
	public function delete($id){
		if(!empty($id)){
			$this->db->delete('options', array('id_type' => $id)); 
			return $this;
		}
	
	}
}